/**
 * @file remove_nth_node_from_end_of_list.cpp
 * @author mixinju@outlook.com
 * @brief 删除倒数第N个结点
 * @version 0.1
 * @date 2021-11-20
 *
 * @copyright Copyright (c) 2021
 *
 */

//题目来源:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

#include "list.h"
/**
 * @brief
 *
 * @param head
 * @param n
 * @return ListNode*
 */
ListNode *removeNthFromEnd(ListNode *head, int n) {
  //使用哑结点，主要是考虑到如果删除的是第一个结点
  ListNode *dummy = new ListNode(0, head);
  ListNode *fast = dummy;
  ListNode *slow = dummy;

  int i = 1;
  while (i <= n && fast) {
    fast = fast->next_;
  }

  if (fast == nullptr) {
    return nullptr;
  }

  while (fast->next_) {
    fast = fast->next_;
    slow = slow->next_;
  }

  ListNode *deleteNode = slow->next_;
  slow->next_ = deleteNode->next_;

  delete deleteNode;

  return dummy->next_;
}